import type { RootThunkAction } from "@/types/store"
import type { UserChannelResponse, Channel, ArticlesResponse } from "@/types/data"
import { http } from "@/utils/http"

const Channel_Key = "geek-channels-138" 
export const getUserChannel = (): RootThunkAction => {
  return async (dispatch, getState) => {

    let userChannels: Channel[] = [] 
    const {
      login: { token },
    } = getState() 
    if (!!token) {
      const {
        data: { channels },
      } = (await http.get("/user/channels")) as UserChannelResponse
      userChannels = channels
    } else {
      const localChannels = JSON.parse(localStorage.getItem(Channel_Key) ?? "[]") as Channel[]
      if (localChannels.length > 0) {
        userChannels = localChannels
      } else {
        const {
          data: { channels },
        } = (await http.get("/user/channels")) as UserChannelResponse
        localStorage.setItem(Channel_Key, JSON.stringify(channels)) 
        userChannels = channels
      }
    }
    dispatch({ type: "home/getUserChannel", payload: userChannels })
  }
}


export const getArticleList = (channel_id: number, timestamp: string, actionType: "append" | "replace"): RootThunkAction => {
  return async (dispatch) => {
    const res = (await http.get("/articles", {
      params: {
        channel_id,
        timestamp,
      },
    })) as ArticlesResponse

    dispatch({
      type: "home/getChannelArtciles",
      payload: { channel_id, data: res.data, actionType },
    })
  }
}
